#  jtvdump.py - part of JtvDump
#  Copyright (C) 2012  Dustin Escoffery
#
#  JtvDump is free software: you can redistribute it and/or
#  modify it under the terms of the Lesser GNU General Public License
#  as published by the Free Software Foundation, version 3 of the
#  license.
#
#  JtvDump is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  Lesser GNU General Public License for more details.
#
#  You should have received a copy of the Lesser GNU General Public
#  License along with JtvDump.  If not, see:
#      http://www.gnu.org/licenses/lgpl-3.0.txt
#
#  CONTRIBUTORS:
#      Dustin Escoffery

import re
import sys, subprocess
import httplib, urllib
import xml.etree.ElementTree as xml

if len(sys.argv) != 2:
    sys.exit("usage: python jtvdump.py channel")

url = "usher.justin.tv"
req = "/find/" + sys.argv[1] + ".xml?"
params = urllib.urlencode({'type': 'any'})

conn = httplib.HTTPConnection(url)
conn.request("GET", req+params)
response = conn.getresponse()
data  = response.read()
conn.close()

# Response is not well-formed, can't have numeric tags like 320p
data = re.sub('(</*)([0-9])', '\g<1>_\g<2>', data)

nodes = xml.fromstring(data)
nodes = [(n, n.find("play"), n.find("token"), n.find("connect"), \
  n.find("bitrate")) for n in list(nodes)]
nodes = filter(lambda n: all(map(lambda x: x is not None, n)), nodes)
nodes = sorted(nodes, key=lambda x: float(x[4].text), reverse=True)

if nodes:
  play = nodes[0][1].text
  token = nodes[0][2].text
  connect = nodes[0][3].text
  swf = "http://www-cdn.jtvnw.net/widgets/live_site_player.swf"
  subprocess.call(["rtmpdump", "--live", "-y", play, "-j", token, \
    "-r", connect, "-s", swf])
